package com.qiyebox.web.controller.biz;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiyebox.common.utils.http.HttpUtils;
import com.qiyebox.system.domain.MeetingText;
import com.qiyebox.system.domain.TextDetail;
import com.qiyebox.system.service.IMeetingTextService;
import com.qiyebox.system.service.ITextDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qiyebox.common.annotation.Log;
import com.qiyebox.common.enums.BusinessType;
import com.qiyebox.system.domain.Meeting;
import com.qiyebox.system.service.IMeetingService;
import com.qiyebox.common.core.controller.BaseController;
import com.qiyebox.common.core.domain.AjaxResult;
import com.qiyebox.common.utils.poi.ExcelUtil;
import com.qiyebox.common.core.page.TableDataInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
/**
 * 【请填写功能名称】Controller
 * 
 * @author qiyebox
 * @date 2025-01-17
 */
@Controller
@RequestMapping("/system/meeting")
@Api("会议管理接口")
public class MeetingController extends BaseController
{
    private String prefix = "system/meeting";

    @Autowired
    private IMeetingService meetingService;

    @Autowired
    private IMeetingTextService meetingTextService;

    @Autowired
    private ITextDetailService textDetailService;

//    @RequiresPermissions("system:meeting:view")
    @GetMapping()
    public String meeting()
    {
        return prefix + "/meeting";
    }

    /**
     * 查询【请填写功能名称】列表
     */
//    @RequiresPermissions("system:meeting:list")
    @PostMapping("/list")
    @ResponseBody
    @ApiOperation("会议列表接口")
    public TableDataInfo list(Meeting meeting)
    {
        startPage();
        List<Meeting> list = meetingService.selectMeetingList(meeting);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:meeting:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Meeting meeting)
    {
        List<Meeting> list = meetingService.selectMeetingList(meeting);
        ExcelUtil<Meeting> util = new ExcelUtil<Meeting>(Meeting.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
//    @RequiresPermissions("system:meeting:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
//    @RequiresPermissions("system:meeting:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @ApiOperation("会议新增接口")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Meeting meeting)
    {
        return toAjax(meetingService.insertMeeting(meeting));
    }

    /**
     * 修改【请填写功能名称】
     */
//    @RequiresPermissions("system:meeting:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Meeting meeting = meetingService.selectMeetingById(id);
        mmap.put("meeting", meeting);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
//    @RequiresPermissions("system:meeting:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation("会议修改接口")
    @ResponseBody
    public AjaxResult editSave(Meeting meeting)
    {
        return toAjax(meetingService.updateMeeting(meeting));
    }

    /**
     * 删除【请填写功能名称】
     */
//    @RequiresPermissions("system:meeting:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ApiOperation("会议删除接口")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(meetingService.deleteMeetingByIds(ids));
    }

    public static final String APP_KEY = "IGiAbiv5nEMzz91g";
    public static final String AK = "LTAI5tGm6RrMiA7JVwD2gWJQ";
    public static final String SK = "BeThEzcd4aUVmKdnKx4TrkzVNOdlzH";
    @GetMapping("/startTask/{id}")
    @ApiOperation("阿里听悟AI转写接口创建")
    @ResponseBody
    public JSONObject startTask(@PathVariable("id") Long id) throws ClientException {
        Meeting meeting = meetingService.selectMeetingById(id);
        if (meeting.getAliTask() != null && meeting.getAliTask().trim().length() > 0) {
            return JSONObject.parseObject(meeting.getAliTask());
        }
        CommonRequest request = createCommonRequest("tingwu.cn-beijing.aliyuncs.com", "2023-09-30", ProtocolType.HTTPS, MethodType.PUT, "/openapi/tingwu/v2/tasks");
        request.putQueryParameter("type", "realtime");

        JSONObject root = new JSONObject();
        root.put("AppKey", APP_KEY);

        JSONObject input = new JSONObject();
        input.fluentPut("SourceLanguage", "cn").fluentPut("Format", "pcm").fluentPut("SampleRate", 16000).fluentPut("TaskKey", "task" + System.currentTimeMillis());
        root.put("Input", input);

        JSONObject parameters = initRequestParameters();
        root.put("Parameters", parameters);

        System.out.println(root.toJSONString());
        request.setHttpContent(root.toJSONString().getBytes(), "utf-8", FormatType.JSON);

        // TODO 请通过环境变量设置您的AccessKeyId、AccessKeySecret
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", AK,  SK);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
        JSONObject body = JSONObject.parseObject(response.getData());
        JSONObject data = (JSONObject) body.get("Data");
        System.out.println("TaskId = " + data.getString("TaskId"));
        System.out.println("MeetingJoinUrl = " + data.getString("MeetingJoinUrl"));
        meeting.setAliTask(data.toJSONString());
        meetingService.updateMeeting(meeting);
        return data;
    }

    private static JSONObject initRequestParameters() {
        JSONObject parameters = new JSONObject();

        // 音视频转换： 可选
        JSONObject transcoding = new JSONObject();
        //transcoding.put("TargetAudioFormat", "mp3");
        //transcoding.put("SpectrumEnabled", false);
        parameters.put("Transcoding", transcoding);

        // 语音识别
        JSONObject transcription = new JSONObject();
        // transcription.put("DiarizationEnabled", true);
        // JSONObject speakerCount = new JSONObject();
        // speakerCount.put("SpeakerCount", 0);
        // transcription.put("Diarization", speakerCount);
        transcription.put("RealtimeDiarizationEnabled", true);
        // 设置语音识别结果返回等级。
        transcription.put("OutputLevel", 2);
        parameters.put("Transcription", transcription);

        // 翻译： 可选
        JSONObject translation = new JSONObject();
        JSONArray langArry = new JSONArray();
        langArry.add("en");
        translation.put("TargetLanguages", langArry);
        parameters.put("Translation", translation);
        parameters.put("TranslationEnabled", false);

        // 章节速览： 可选
        parameters.put("AutoChaptersEnabled", true);

        // 智能纪要： 可选
        parameters.put("MeetingAssistanceEnabled", true);

        // 摘要相关： 可选
        parameters.put("SummarizationEnabled", true);
        JSONObject summarization = new JSONObject();
        JSONArray types = new JSONArray().fluentAdd("Paragraph").fluentAdd("Conversational").fluentAdd("QuestionsAnswering").fluentAdd("MindMap");
        summarization.put("Types", types);
        parameters.put("Summarization", summarization);

        // PPT抽取： 不可选，实时记录没有视频信息，无法进行ppt功能
        // parameters.put("PptExtractionEnabled", false);

        // 口语书面化：可选
        parameters.put("TextPolishEnabled", false);

        return parameters;
    }
    public static CommonRequest createCommonRequest(String domain, String version, ProtocolType protocolType, MethodType method, String uri) {
        CommonRequest request = new CommonRequest();
        request.setSysDomain(domain);
        request.setSysVersion(version);
        request.setSysProtocol(protocolType);
        request.setSysMethod(method);
        request.setSysUriPattern(uri);
        request.setHttpContentType(FormatType.JSON);
        return request;
    }

    @GetMapping("/stopTask/{id}")
    @ApiOperation("阿里听悟AI转写接口结束")
    @ResponseBody
    public String stopTask(@PathVariable("id") Long id) throws ClientException {
        Meeting meeting = meetingService.selectMeetingById(id);
        String taskId = JSONObject.parseObject(meeting.getAliTask()).getString("TaskId");
        CommonRequest request = createCommonRequest("tingwu.cn-beijing.aliyuncs.com", "2023-09-30", ProtocolType.HTTPS, MethodType.PUT, "/openapi/tingwu/v2/tasks");
        request.putQueryParameter("type", "realtime");
        // 必须设置 operation=stop
        request.putQueryParameter("operation", "stop");

        JSONObject root = new JSONObject();
        JSONObject input = new JSONObject();
        input.put("TaskId", taskId);
        root.put("Input", input);
        System.out.println(root.toJSONString());
        request.setHttpContent(root.toJSONString().getBytes(), "utf-8", FormatType.JSON);

        // TODO 请通过环境变量设置您的AccessKeyId、AccessKeySecret
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", AK,  SK);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
//        meeting.setAliTask("");
//        meetingService.updateMeeting(meeting);
        saveText(taskId, meeting);
        return response.getData();
    }

    @GetMapping("/getTaskInfo/{taskId}")
    @ApiOperation("阿里听悟AI转写任务查看")
    @ResponseBody
    public String getTask(@PathVariable("taskId") String taskId) throws ClientException {
//        String taskId = "34483153e68e41de8149088e40962196";
        return getTaskInfo(taskId);
    }

    private void saveText(String taskId, Meeting meeting) {
        try {
            String taskInfo = getTaskInfo(taskId);
            String url = JSONObject.parseObject(taskInfo).getJSONObject("Data").getJSONObject("Result").getString("Transcription");

            MeetingText meetingText = new MeetingText();
            meetingText.setName(meeting.getTitle() + "字幕");
            meetingText.setCreateAt(new Date());
            meetingText.setMeetingId(meeting.getId());
            meetingTextService.insertMeetingText(meetingText);

            String data = HttpUtils.sendGet(url);
            JSONArray Paragraphs = JSONObject.parseObject(data).getJSONObject("Transcription").getJSONArray("Paragraphs");

            for (int i=0; i<Paragraphs.size(); i++) {
                TextDetail textDetail = new TextDetail();
                textDetail.setContent(Paragraphs.getJSONObject(i).toJSONString());
                textDetail.setMeetingTextId(meetingText.getId());
                textDetail.setType(1l);
                textDetail.setCreateAt(new Date());
                textDetailService.insertTextDetail(textDetail);
            }
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }

    }

    private static String getTaskInfo(String taskId) throws ClientException {
        String queryUrl = String.format("/openapi/tingwu/v2/tasks" + "/%s", taskId);

        CommonRequest request = createCommonRequest("tingwu.cn-beijing.aliyuncs.com", "2023-09-30", ProtocolType.HTTPS, MethodType.GET, queryUrl);
        // TODO 请通过环境变量设置您的AccessKeyId、AccessKeySecret
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", AK, SK);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
        return response.getData();
    }
}
